package br.here.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.here.data.UsuarioDAOImpl;
import br.here.dominio.Usuario;
import br.here.exceptions.BDException;
import br.here.negocio.UsuarioCadastro;

/**
 * Servlet implementation class ServletAndroid
 */
public class ServletAndroid extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletAndroid() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String senha = request.getParameter("senha");
		String nome = request.getParameter("nome");
		UsuarioCadastro uCad = new UsuarioCadastro(new UsuarioDAOImpl());
		if (nome == null || nome.equals("")){
			try {
				Usuario usuario = uCad.findByEmail(email);
				if (usuario != null){
					if (usuario.getSenha().equals(senha)){
						response.getWriter().print("sucesso");
					} else {
						response.getWriter().print("falha");
					}
				}
				else
					response.getWriter().print("falha");
			} catch (BDException e) {
				response.getWriter().print("falha");
			} finally{
				response.getWriter().flush();
				response.getWriter().close();
			}
		} else {
			try {
				Usuario u = new Usuario();
				u.setNome(nome);
				u.setEmail(email);
				u.setSenha(senha);
				uCad.addUsuario(u);
				response.getWriter().print("sucesso");
			} catch (Exception e ){
				response.getWriter().print("falha");
			}finally {
				response.getWriter().flush();
				response.getWriter().close();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		UsuarioCadastro uCad = new UsuarioCadastro(new UsuarioDAOImpl());
		try {
			Usuario usuario = uCad.findByEmail(email);
			if (usuario != null)
				response.getWriter().print("sucesso");
			else
				response.getWriter().print("falha");
		} catch (BDException e) {
			response.getWriter().print("falha");
		} finally{
			response.getWriter().flush();
			response.getWriter().close();
		}
		
	}

}
